//
//  JGTWeatherViewController.m
//  RunningMan
//
//  Created by JGT on 16/6/2.
//  Copyright © 2016年 WSJ. All rights reserved.
//

#import "JGTWeatherViewController.h"
#import "AppDelegate.h"
#import "JGTCityTableViewController.h"
#import "JGTView.h"
#import "JGTNow.h"
#import "JGTDaily.h"
#import "JGTNetWorking.h"
#import "JGTDataTool.h"
#import "JGTHourly.h"
#import "JGTLocationTool.h"
#import <CoreLocation/CoreLocation.h>
#import "MJRefresh.h"
#import <UIImageView+WebCache.h>
#import "WSJSweepViewController.h"
#import <AVFoundation/AVFoundation.h>
@interface JGTWeatherViewController ()<UITableViewDataSource,UITableViewDelegate,UIImagePickerControllerDelegate,UINavigationControllerDelegate>

@property (nonatomic, strong)UITableView *tableView;
@property (nonatomic, strong)NSArray *dailyArray;
@property (nonatomic, strong)NSArray *hourlyArray;
@property (nonatomic, strong)JGTView *headView;
@property (nonatomic, strong)JGTNow *nowData;
@property (nonatomic, strong)CLLocation *userLocation;
@property (nonatomic, strong)UIImageView *backImageView;
@property (nonatomic, strong)UIButton *Sbtn;
@end

@implementation JGTWeatherViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view from its nib.
 
    self.navigationItem.leftBarButtonItem = [[UIBarButtonItem alloc]initWithImage:[UIImage imageNamed:@"login.png"] style:UIBarButtonItemStylePlain target:self action:@selector(login)];

    self.navigationItem.rightBarButtonItem = [[UIBarButtonItem alloc]initWithTitle:@"切换城市" style:UIBarButtonItemStylePlain target:self action:@selector(weather)];
    
    self.navigationController.navigationBar.translucent = NO;
  
    [self createBackView];
    [self createTableView];
    [self createHeaderView];
    [self createRefreshControl];
    [self getLocationAndSendRequest];
    
    
    [NOTIFICATION_CENTER addObserver:self selector:@selector(shouldChangeCity:) name:@"DidChangeCity" object:nil];
    
    self.Sbtn = [UIButton buttonWithType:UIButtonTypeCustom];
    [self.Sbtn setImage:[UIImage imageNamed:@"S.PNG"] forState:UIControlStateNormal];
    [self.navigationController.view addSubview:self.Sbtn];
    self.Sbtn.frame = CGRectMake(60, 22, 40, 40);
    [_Sbtn addTarget:self action:@selector(sweep) forControlEvents:UIControlEventTouchUpInside];
}
- (void)viewWillAppear:(BOOL)animated{
    
    self.Sbtn.hidden = NO;
    
}
- (void)viewWillDisappear:(BOOL)animated{
    self.Sbtn.hidden = YES;
}
- (void)sweep{
    
    
    WSJSweepViewController *Sweep = [[WSJSweepViewController alloc] init];
    [self.navigationController pushViewController:Sweep animated:YES
     
     ];
}
//- (void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary<NSString *,id> *)info {
//    [picker dismissViewControllerAnimated:true completion:^{
//        UIImage *image = info[UIImagePickerControllerEditedImage];
//        if (!image) {
//            image = info[UIImagePickerControllerOriginalImage];
//        }
//        
//        NSData *imageData = UIImageJPEGRepresentation(image, 1);
//        
//        // kCIContextUseSoftwareRenderer : 软件渲染 -- 可以消除 "BSXPCMessage received error for message: Connection interrupted" 警告
//        // kCIContextPriorityRequestLow : 低优先级在 GPU 渲染-- 设置为false可以加快图片处理速度
//        CIContext *context = [CIContext contextWithOptions:@{kCIContextUseSoftwareRenderer : @(true), kCIContextPriorityRequestLow : @(false)}];
//        
//        CIDetector *detector = [CIDetector detectorOfType:CIDetectorTypeQRCode context:context options:nil];
//        CIImage *ciImage = [CIImage imageWithData:imageData];
//        
//        NSArray *ar = [detector featuresInImage:ciImage];
//        CIQRCodeFeature *feature = [ar firstObject];
//        NSLog(@"detector: %@", detector);
//        NSLog(@"context: %@", feature.messageString);
//        UIAlertController *alert = [UIAlertController alertControllerWithTitle:nil message:[NSString stringWithFormat:@"扫描结果：%@", feature.messageString ?: @"空"] preferredStyle:UIAlertControllerStyleAlert];
//        [alert addAction:[UIAlertAction actionWithTitle:@"Sure" style:UIAlertActionStyleCancel handler:nil]];
//        [self presentViewController:alert animated:true completion:nil];
//        
//    }];
//}
//
//
//- (void)imagePickerControllerDidCancel:(UIImagePickerController *)picker {
//    [picker dismissViewControllerAnimated:true completion:nil];
//}

- (void)shouldChangeCity:(NSNotification *)notification{
    NSString *cityName = notification.userInfo[@"cityName"];
    [self sendRequestToServer:cityName];
    
}
- (void)weather{
    JGTCityTableViewController *jgtVC = [[JGTCityTableViewController alloc]init];
    [self.navigationController pushViewController:jgtVC animated:YES];
    
    
}

- (void)login{
    AppDelegate *temp = (AppDelegate *)[[UIApplication sharedApplication]delegate];
    if (temp.LeftSlideVC.closed) {
        [temp.LeftSlideVC openLeftView];
    }else{
        [temp.LeftSlideVC closeLeftView];
        
    }
}
- (void)createHeaderView{
    self.headView = [[JGTView alloc]initWithFrame:CGRectMake(0, 0, SCREEN_WIDTH, 300)];
    self.tableView.tableHeaderView = self.headView;
    
}
- (void)createBackView{
    self.backImageView = [[UIImageView alloc]initWithImage:[UIImage imageNamed:@"456.jpg"]];
    _backImageView.frame = SCREEN_BOUNDS;
    [self.view addSubview:self.backImageView];
    
}
- (void)createTableView{
    self.tableView = [UITableView new];
    self.tableView.frame = CGRectMake(0, 0, SCREEN_WIDTH, SCREEN_HEIGHT - 113);
    self.tableView.dataSource = self;
    self.tableView.delegate = self;
    self.tableView.separatorStyle = NO;
    self.tableView.showsVerticalScrollIndicator = NO;
    self.tableView.backgroundColor = [UIColor clearColor];
    [self.view addSubview:self.tableView];
    
}
- (void)getLocationAndSendRequest{
    [JGTLocationTool getUserLocation:^(double lat, double lon, NSString *cityName) {
        CLLocation *location = [[CLLocation alloc]initWithLatitude:lat longitude:lon];
        self.userLocation = location;
        [self sendRequestToServer:cityName];
        [self  updateHearderView:cityName];
        
    }];
    
    
}
- (void)createRefreshControl{
    MJRefreshNormalHeader *header = [MJRefreshNormalHeader headerWithRefreshingTarget:self refreshingAction:@selector(getLocationAndSendRequest)];
    header.lastUpdatedTimeLabel.hidden = YES;
    [header beginRefreshing];
    self.tableView.mj_header = header;
    
    
}
- (void)updateHearderView:(NSString *)cityName{
    self.headView.cityLabel.text = cityName;
    if (self.nowData.iconCodeUrl && self.nowData.tmp && self.dailyArray[0]) {
        self.headView.temperatureLabel.text = self.nowData.tmp;
        JGTDaily *daily =self.dailyArray[0];
        self.headView.hiloLabel.text = [NSString stringWithFormat:@"%@/%@",daily.min,daily.max];
        self.headView.conditionsLabel.text = self.nowData.qlty;
        [self.headView.iconView sd_setImageWithURL:[NSURL URLWithString:self.nowData.iconCodeUrl] placeholderImage:[UIImage imageNamed:@"999"]];
    }
    
    
}
//发送请求数据
- (void)sendRequestToServer:(NSString *)cityName
{
    
    //设置TSMessage默认控制器
    //    [TSMessage setDefaultViewController:self];
    //URL
    NSString *baseUrl = @"https://api.heweather.com/x3/weather";
    NSMutableDictionary *params = [NSMutableDictionary dictionary];
    params[@"city"] = cityName;
    params[@"key"] = @"6597349262e94aecbbca2e27c9bd948d";
    //NetworkManager
    [JGTNetWorking sendGetRequestWithUrl:baseUrl parameters:params success:^(id responseObject) {
        //TYLog(@"服务器返回的json数据:%@",responseObject);
        //返回每日天气
        //返回小时天气
        self.dailyArray = [JGTDataTool getAllDailyData:responseObject];
        self.hourlyArray = [JGTDataTool getAllHourlyData:responseObject];
        self.nowData = [JGTDataTool getNowData:responseObject];
        //刷新tableView
        [self.tableView reloadData];
        [self updateHearderView:cityName];
        [self.tableView.mj_header endRefreshing];
    } failure:^(NSError *error) {
       
        [self.tableView.mj_header endRefreshing];
    }];
}
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView{
    return 2;
    
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    return section == 0 ? self.hourlyArray.count + 1 : self.dailyArray.count + 1;
    
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    static NSString *iden = @"cell";
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:iden];
    if (!cell) {
        cell = [[UITableViewCell alloc]initWithStyle:UITableViewCellStyleValue1 reuseIdentifier:iden];
    }
    cell.backgroundColor = [UIColor clearColor];
    cell.textLabel.textColor = [UIColor blackColor];
    cell.selectionStyle = UITableViewCellSelectionStyleNone;
    if (indexPath.section == 0) {
        if (indexPath.row == 0) {
            cell.textLabel.text = @"未来几小时天气";
            cell.detailTextLabel.text = nil;
            cell.imageView.image = nil;
        } else {
            JGTHourly *hourly = self.hourlyArray[indexPath.row - 1];
            cell.imageView.image = nil;
            cell.textLabel.text = hourly.time;
            cell.detailTextLabel.text = hourly.tmp;
            
        }
    } else {
        if (indexPath.row == 0) {
            cell.textLabel.text = @"未来一周天气";
            cell.detailTextLabel.text = nil;
            cell.imageView.image = nil;
        } else {
            JGTDaily *daily = self.dailyArray[indexPath.row - 1];
            cell.textLabel.text = daily.date;
            cell.detailTextLabel.text = [NSString stringWithFormat:@"%@ / %@", daily.max, daily.min];
            //下载图片
            [cell.imageView sd_setImageWithURL:[NSURL URLWithString:daily.iconUrl] placeholderImage:[UIImage imageNamed:@"placeholder"]];
        }
    }
    return cell;
}
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    NSInteger rowCount = [self tableView:tableView numberOfRowsInSection:indexPath.section];
    return SCREEN_HEIGHT / rowCount;
    
    
}
- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
